<template>
  <div class="app-container">


    <!-- vxe检索数据组件 -->
    <search-form
      ref="searchForm"
      :formSearchData.sync="formSearchData"

      @searchEventEmit="searchEventEmit"
      @resetSearchEventEmit="resetSearchEventEmit"
    >
    </search-form>


    <!-- 表格组件 -->
    <ex-base-table
      ref="exBaseTable"
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading.sync="loading"
      :isVxeColSeq="false"
      :handleColsWidth="350"
      :isVxeCheckbox="false"
      @handleCreateEmit="handleCreateEmit"
      @handleUpdateEmit="handleUpdateEmit"
      @handleRmoveColEmit="handleRmoveColEmit"
      @customSortMethodEmit="customSortMethodEmit"
    >

      <!-- 操作栏按钮扩展插槽 -->
      <template v-slot:handleExtend="{row}">
        <!-- &nbsp;
        <el-button v-if="true" size="mini" type="text" @click="viewFactor(row)">
          组成因子
        </el-button> -->
        &nbsp;
        <el-button v-if="true" size="mini" type="text" @click="viewSonTable(row)">
          流程
        </el-button>
        &nbsp;
        <el-button v-if="true" size="mini" type="text" @click="viewPerformedManually(row)">
          手动执行
        </el-button>
        <!-- &nbsp;
        <el-button v-if="true" size="mini" type="text" @click="viewCopyBookScheme(row)">
          复制
        </el-button>
        &nbsp;
        <el-button v-if="true" size="mini" type="text" @click="exportBookScheme(row)">
          导出
        </el-button> -->
      </template>

    </ex-base-table>

    <!-- 分页组件 -->
    <Pagination
      v-show="tablePage.totalResult>0"
      :total="tablePage.totalResult"
      :page.sync="tablePage.currentPage"
      :limit.sync="tablePage.pageSize"
      @pagination="pageFindList"
    />


    <!-- 表单提价组件 -->
    <submit-form
      ref="submitForm"
      :dialogFormVisible.sync="dialogFormVisible"
      :dialogStatus="dialogStatus"
      :formSubmitData="formSubmitData"
      :lpOptions="lpOptions"
      @handleFromUpdateDataEmit="handleFromUpdateDataEmit"
      @handleFromCreateDataEmit="handleFromCreateDataEmit"
      @resetFormDataEmit="resetFormSubmitData"
      @handleFromCopysDataEmit="handleFromCopysDataEmit"
    >
    </submit-form>


    <!-- 弹框表格-树状表格 -->
    <el-dialog
      :title="dialogSonTableVisible_title"
      width="80%"
      :visible.sync="dialogSonTableVisible"
    >
      <BookOfAccountTable
        ref="bookOfAccountTable"
        :currentRow="currentRow"
        :factorSelected="factorSelected"
      />
    </el-dialog>

    <!-- 弹框表单-组成因子 -->
    <el-dialog
      title="组成因子"
      width="827px"
      :visible.sync="dialogFactorVisible"
      >
      <FactorTransfer
        :titles="['因子(未选)','因子(已选)']"
        :value.sync="factorValue"
        :data="factorData"
        :currentRow="currentRow"
        @factortransferEmit="factortransferEmit"
      />

    </el-dialog>


    <SubmitFormPerformedManually 
      ref="submitFormPerformedManually"
      :dialogFormVisible.sync="dialogFormVisiblePerformedManually"
      :dialogStatus="dialogStatusPerformedManually"
      :formSubmitData="formSubmitDataPerformedManually"
      @handleFromManuallyDataEmit="handleFromManuallyDataEmit"
      />

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'

import {
  addTask,
  addfactor,
  delTask,
  // delTaskBatch,
  findTask,
  updateTask,
  PerformedManually,



  fingfactorcodename,
  fingfactorcodenamein,
  copycoaplan,
  addTask_code
} from './service/baseApi'
// 基础表格组件
import ExBaseTable from '@/components/VxeTable/ExBaseTable'
// 分页
import Pagination from '@/components/Pagination'
// 文章表单
import SubmitForm from './components/SubmitForm'
// 检索表单
import SearchForm from './components/SearchForm'
// 子表格
import BookOfAccountTable from './components/BookOfAccountTable'
// 组成因子组件
import FactorTransfer from './components/FactorTransfer'

import SubmitFormPerformedManually from './components/SubmitFormPerformedManually'


import XEUtils from 'xe-utils'

import cvoptions from '@/views/CurveManageNew/mixins/cvoptions'
import resetFormSubmitData from '@/views/mixins/resetFormSubmitData'



export default {
  name: 'vxe-basetable',

  mixins: [cvoptions, resetFormSubmitData],

  components: {
    //PageHeaderLayout,
    ExBaseTable,
    Pagination,
    SubmitForm,
    SearchForm,
    BookOfAccountTable,
    FactorTransfer,
    SubmitFormPerformedManually
  },
  // 定义属性
  data() {
    const XEUtilsLocat = XEUtils.locat()
    const hostName = XEUtilsLocat.hostname
    const protocol = XEUtilsLocat.protocol

    return {
       /* host信息 */
      hostName: hostName,
      protocol: protocol,

      // 检索条件
      formSearchData: {
        task_code: '',
        task_name: '',
      },

      // 排除条件
      sortField: '',
      sortFlag: '',

      /* 表单相关 */
      dialogFormVisible: false, // 修改删除弹出框
      dialogStatus: '',
      // 表单数据对象
      formSubmitData: {
        id: undefined,
        task_code: '', //曲线编号
        task_name: '', //曲线名称
        exct_fqc:'',
        lp_code: '123456', // TODO: ss
        status: '1', //期限方案
        remark: '', //备注
      },
      initFormSubmitData: {
        id: undefined,
        task_code: '', //曲线编号
        task_name: '', //曲线名称
        exct_fqc:'',
        lp_code: '123456', // TODO: ss
        status: '1', //期限方案
        remark: '', //备注
      },
      /* 分页相关 */
      tablePage: {
        currentPage: 1, //当前页
        pageSize: 10,  // 每一页页数
        totalResult: 0
      },
      /* 表格相关 */
      tableColumn: [], // 表格字段
      loading: false, //表格loading特效
      tableData: [],  //表格数据
      currentRow: {},
      /* 弹框状态-树状表格 */
      dialogSonTableVisible: false,
      dialogSonTableVisible_title:'',
      /* 弹框状态-组成因子 */
      dialogFactorVisible: false,
      factorValue: [1001],
      factorSelected: [],
      factorData: [
        {
          label: '科目因子科目因子科目因子科目因子科目因子科目因子科目因子',
          key: 1001,
          disabled: false
        },
        {
          label: '机构因子',
          key: 1002,
          disabled: false
        },
        {
          label: '产品因子',
          key: 1003,
          disabled: false
        }

      ],

      /* 手动执行 */
      dialogStatusPerformedManually: 'manually',
      dialogFormVisiblePerformedManually :false,
      formSubmitDataPerformedManually:{
        id: undefined,
        s_date:'',
        e_date:''
      }

    } //datareturn-end
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {

    /* API数据操作相关 */
    async getAddTask_code() {
      return await addTask_code().then(({data}) => {
        return data.rows.task_code
      })
    },
    // 所有因子
    findFingfactorcodename() {
      fingfactorcodename().then(({data}) => {
        this.factorData = XEUtils.map(data.rows, (item) => {
          return {
            label: `${item.factor_code}-${item.factor_name}`,
            key: item.factor_code,
            disabled: false
          }
        })
      })
    },
    // 已选因子
    findFingfactorcodenamein() {
      fingfactorcodenamein({id: this.currentRow.id}).then(({data}) => {
        this.factorSelected = data.rows
        console.log('xingxing ', this.factorSelected);
        this.factorValue = []
        XEUtils.arrayEach(data.rows, (item, key) => {
          this.factorValue.push(item.factor_code)
        })
      })
    },
    // 修改因子
    modifyAddfactor(factor_code) {
      addfactor({
        id: this.currentRow.id,
        factor_code
      })
    },
    /* 曲线参数修改 */
    factortransferEmit(val) {
      this.modifyAddfactor(val.join(','))
    },
    // 查询数据
    findList() {
      this.loading = true
      console.log(' this.formSearchData:::', this.formSearchData);
      console.log('打印当前页：：：：', this.tablePage.currentPage);
      // 请求表格数据
      findTask({
        page: this.tablePage.currentPage, // 当前页
        pageSize: this.tablePage.pageSize, // 每页条数
        //  sort:this.sortData,
        sortField: this.sortField,
        sortFlag: this.sortFlag,
        // sort:JSON.stringify(this.sortData),
        ...this.formSearchData,  //检索条件
      }).then(({data}) => {
        console.log('response:....', data);
        // 给表格数据赋值
        this.tableData = data.rows
        // 给分页总数赋值
        this.tablePage.totalResult = data.total
        // 关闭加载特效
        setTimeout(() => {
          this.loading = false
        }, 0.5 * 1000)
      })
    },
    /* 分页组件相关 */
    // 分页事件（页码切换，每页页数切换）
    pageFindList() {
      this.findList()
    },
    /* 表格组件相关 */
    // 初始化表格字段
    initTableCols() {
      const tabCols = [  //动态增加的字段 传进来的
        // { type: 'seq', width: 60, fixed: null },
        // { type: 'checkbox', width: 50, fixed: null },
        {field: 'lp_name', title: '所属法人', width: 300},
        {field: 'task_code', title: '任务方案编码', width: 300},
        {field: 'task_name', title: '任务方案名称', width: 300},
        // {field: 'exct_fqc', title: '跑批频率', width: 300},
        {
          field: 'status', title: '状态', width: 300, formatter(obj) {
            if (obj.cellValue == 1) {
              return "有效"
            } else {
              return "无效"
            }
          }
        },
        {field: 'remark', title: '备注', width: 300},



        // {field: 'coa_plan_code', title: '账户册方案编码', width: 200, showOverflow: true, sortable: true},
        // {field: 'coa_plan_name', title: '账户册方案名称', width: 300},
        // {field: 'lp_name', title: '所属法人', width: 200, sortable: true},
        // {
        //   field: 'status', title: '状态', width: 300, formatter(obj) {
        //     if (obj.cellValue == 1) {
        //       return "有效"
        //     } else {
        //       return "无效"
        //     }
        //   }
        // },
        // {field: 'remark', title: '备注', width: 200, sortable: true},
      ]
      this.tableColumn = tabCols;
    },
    // 表格工具组-新增表单弹窗（需要表单组件）
    handleCreateEmit(type) {

      this.getAddTask_code().then((task_code) => {
        // 重置表单内容
        this.resetFormSubmitData({
          replaceObj: {
            task_code
          }
        })
        this.dialogStatus = type
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.submitForm.$refs['dataForm'].clearValidate()
        })
      })
    },
    // 行内按钮-修改数据弹窗（需要表单组件）
    handleUpdateEmit(row, type) {
      this.formSubmitData = Object.assign({}, row) // copy obj
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 单行删除
    handleRmoveColEmit(row) {
      console.log("AJAX 请求删除单行数据");
      // this.$refs.exBaseTable.$refs.xTable.remove(row)
      delTask({
        id: row.id
      }).then(({data}) => {
        console.log('response:....', data);

        this.findList()
        // 关闭加载特效

      })
    },
    /* 表单组件相关 */
    // 更新
    handleFromUpdateDataEmit() {
      updateTask({
        ...this.formSubmitData, 
      }).then(({data}) => {
        this.findList()
      })
    },
    // 增加
    handleFromCreateDataEmit() {
      addTask({
        ...this.formSubmitData, 
      }).then(({data}) => {
        this.findList()
      })
    },

    /* 检索相关 */
    // 检索
    searchEventEmit() {
      this.tablePage.currentPage = 1
      console.log("searchEventEmit", this.formSearchData);
      this.findList()
    },
    // 重置
    resetSearchEventEmit() {
      // 重置代码...
      console.log("resetSearchEventEmit", this.formSearchData);
      this.tablePage.currentPage = 1
      this.findList()
    },
    /* 排序 */
    customSortMethodEmit(property, order) {
      // this.sortData[`${property}`] = order
      this.sortField = property
      this.sortFlag = order
      console.log('触发排序emit');
      this.findList()
      console.log(this.sortData);
    },


    /* 子表格弹出 */
    viewSonTable(row) {
      this.currentRow = Object.assign({}, row) // copy obj
      this.findFingfactorcodenamein()
      this.dialogSonTableVisible_title = row.task_name
      this.dialogSonTableVisible = true
    },
    /* 组成因子弹出 */
    viewFactor(row) {
      this.currentRow = Object.assign({}, row) // copy obj

      this.findFingfactorcodename()
      this.findFingfactorcodenamein()


      this.dialogFactorVisible = true
    },
    /* 导出 */
    exportBookScheme(row){
      window.location.href = `${this.protocol}//${this.hostName}:7001/${process.env.VUE_APP_DATA_IO_URI_PARAM}/AccountBookScheme/derivePricingrules?id=${row.id}`
    },
    
    /* 手动执行 */
    viewPerformedManually(row){
      // 重置表单内容
      // this.resetFormSubmitData({
      //   replaceObj: {
      //     id: row.id, //曲线名称
      //   },
      // })
      this.$set(this.formSubmitDataPerformedManually,'id',row.id)
      this.dialogStatusPerformedManually = 'manually'
      this.dialogFormVisiblePerformedManually = true
      this.$nextTick(() => {
        this.$refs.submitFormPerformedManually.$refs['dataForm'].clearValidate()
      })
    },
    handleFromManuallyDataEmit(){
      PerformedManually({
        ...this.formSubmitDataPerformedManually, 
      }).then(({data}) => {
        this.findList()
      })
    },
    /* 复制 */
    viewCopyBookScheme(row){
      // 重置表单内容
      this.resetFormSubmitData({
        replaceObj: {
          id: row.id, //曲线名称
        },
      })
      this.dialogStatus = 'copys'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    handleFromCopysDataEmit(){
      copycoaplan({
        ...this.formSubmitData, 
      }).then(({data}) => {
        this.findList()
      })
    }
  }, //method-end
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 初始化表格字段
    this.initTableCols()
    // 初始化表格数据
    this.findList()

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>


.my-dropdown4 {
  width: 600px;
  height: 300px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>